package com.systop.tea.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.systop.tea.common.R;
import com.systop.tea.entity.Admin;
import com.systop.tea.service.AdminService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequiredArgsConstructor
@RequestMapping("/admin")
public class AdminController {

	private final AdminService adminService;

	@PostMapping("/login")
	public R<Admin> login(@RequestBody Admin admin, HttpSession session) {
		LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(Admin::getUsername, admin.getUsername());
		queryWrapper.eq(Admin::getPassword, admin.getPassword());
		Admin admin1 = adminService.getOne(queryWrapper);
		if (admin1 == null) {
			return R.error("账号或密码错误");
		} else if (admin1.getStatus().equals("0")) {
			return R.error("管理员已被禁用");
		} else {
			session.setAttribute("admin", admin1);
			return R.success(admin1);
		}
	}

	@GetMapping("/logout")
	public R<String> logout(HttpSession session) {
		if (session != null) {
			session.removeAttribute("admin");
			session.invalidate();
		}
		return R.success("退出成功");
	}

	// 分页、条件查询
	@GetMapping("/query")
	public R<Page> query(Admin admin, Integer pageNum, Integer pageSize) {
		Page page = new Page(pageNum, pageSize);
		LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.like(StringUtils.isNotBlank(admin.getUsername()), Admin::getUsername, admin.getUsername());
		queryWrapper.eq(StringUtils.isNotBlank(admin.getStatus()), Admin::getStatus, admin.getStatus());
		adminService.page(page, queryWrapper);

		return R.success(page);
	}

	// 根据id查询
	@GetMapping("/{id}")
	public R<Admin> queryById(@PathVariable Integer id) {
		Admin admin = adminService.getById(id);
		return R.success(admin);
	}

	// 添加管理员
	@PostMapping
	public R<String> add(@RequestBody Admin admin) {
		boolean rows = adminService.save(admin);
		if (rows)
			return R.success("员工添加成功");
		else
			return R.error("员工添加失败");
	}

	// 修改管理员
	@PutMapping
	public R<String> modify(@RequestBody Admin admin) {
		boolean rows = adminService.updateById(admin);
		if (rows)
			return R.success("员工修改成功");
		else
			return R.error("员工修改失败");
	}

}
